//
//  CameraView.m
//  XPhoto
//
//  Created by baboy on 2020/5/31.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "CameraView.h"
#import <BKKit/NSDate+x.h>
#import <BKKit/UIImage+x.h>
#import <BKKit/BKNavigationController.h>
#import "PHAsset+x.h"
#import "PhotoEditPreviewViewController.h"

UIImageOrientation UIImageOrientationForCGImagePropertyOrientation(int cgOrientation) {
    switch (cgOrientation) {
        case kCGImagePropertyOrientationUp: return UIImageOrientationUp;
        case kCGImagePropertyOrientationDown: return UIImageOrientationDown;
        case kCGImagePropertyOrientationLeft: return UIImageOrientationLeft;
        case kCGImagePropertyOrientationRight: return UIImageOrientationRight;
        case kCGImagePropertyOrientationUpMirrored: return UIImageOrientationUpMirrored;
        case kCGImagePropertyOrientationDownMirrored: return UIImageOrientationDownMirrored;
        case kCGImagePropertyOrientationLeftMirrored: return UIImageOrientationLeftMirrored;
        case kCGImagePropertyOrientationRightMirrored: return UIImageOrientationRightMirrored;
    }
    return UIImageOrientationUp;
};

@interface CameraView ()<AVCapturePhotoCaptureDelegate,AVCaptureFileOutputRecordingDelegate,PhotoEditPreviewDelegate>
@property(nonatomic, strong) NSTimer *videoTimer;
@property(nonatomic, strong) NSDate *videoRecordStartDate;
@end
@implementation CameraView

- (AVCaptureDevice*)cameraWithPostion:(AVCaptureDevicePosition)position{
    AVCaptureDevice *device = nil;
    AVCaptureDeviceDiscoverySession *discoverySession  = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:position];
    
    NSArray *devicesIOS  = discoverySession.devices;
    for (AVCaptureDevice *device in devicesIOS) {
        if ([device position] == position) {
            return device;
        }
    }
    return device;
}
- (void)setupCaptureSession {
    // 1.获取视频设备
    self.videoDevice = [self cameraWithPostion:AVCaptureDevicePositionBack];
    // 2.获取音频设备
    self.audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    // 3.创建视频输入
    NSError *error = nil;
    self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:self.videoDevice error:&error];
    if (error) {
        return;
    }
    // 4.创建音频输入
    self.audioInput = [AVCaptureDeviceInput deviceInputWithDevice:self.audioDevice error:&error];
    if (error) {
        return;
    }
    // 5.创建视频输出
    
    // 6.建立会话
    if (!_captureSession) {
        _captureSession = [[AVCaptureSession alloc] init];
    }
//    _captureSession.sessionPreset = AVCaptureSessionPreset3840x2160;
//    _captureSession.sessionPreset = AVCaptureSessionPresetPhoto;
    if ([_captureSession canAddInput:self.videoInput]) {
        [_captureSession addInput:self.videoInput];
    }
    if ([_captureSession canAddInput:self.audioInput]) {
        [_captureSession addInput:self.audioInput];
    }
    // 7.预览画面
    if (!_previewLayer) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspect;
        _previewLayer.frame = self.previewView.bounds;
        [self.previewView.layer addSublayer:_previewLayer];
    }
}
/**
 * 视频模式
 */
- (BOOL)setVideoOutputActive{
    NSArray *outputs = [self.captureSession outputs];
    for (AVCaptureOutput *output in outputs) {
        if ([output isKindOfClass:[AVCaptureMovieFileOutput class]]) {
            return YES;
        }
    }
    
    BOOL flag = NO;
    [self.captureSession beginConfiguration];
    AVCaptureMovieFileOutput *videoOutput = [AVCaptureMovieFileOutput new];
    if ([self.captureSession canAddOutput:videoOutput]) {
        [self.captureSession addOutput:videoOutput];
        self.captureSession.sessionPreset = AVCaptureSessionPreset3840x2160;
        self.movieFileOutput = videoOutput;
        flag = YES;
        for (AVCaptureOutput *output in outputs) {
            [self.captureSession removeOutput:output];
        }
    }
    [self.captureSession commitConfiguration];
    return flag;
}
/**
 * 拍照模式
 */
- (BOOL)setPhotoOutputActive{
    NSArray *outputs = [self.captureSession outputs];
    for (AVCaptureOutput *output in outputs) {
        if ([output isKindOfClass:[AVCapturePhotoOutput class]]) {
            return YES;
        }
    }
    
    BOOL flag = NO;
    [self.captureSession beginConfiguration];
    AVCapturePhotoOutput *output = [AVCapturePhotoOutput new];
    output.highResolutionCaptureEnabled = YES;
    if ([self.captureSession canAddOutput:output]) {
        self.captureSession.sessionPreset = AVCaptureSessionPresetPhoto;
        [self.captureSession addOutput:output];
        self.photoOutput = output;
        flag = YES;
        for (AVCaptureOutput *output in outputs) {
            [self.captureSession removeOutput:output];
        }
    }
    [self.captureSession commitConfiguration];
    return flag;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.photos = [NSMutableArray array];
    self.videoClips = [NSMutableArray array];
    [self setupCaptureSession];
    [self setPhotoOutputActive];
    [self startSession];
    
}
- (void)layoutSubviews{
    [super layoutSubviews];
    self.previewLayer.frame = self.previewView.bounds;
    self.videoRecordProgressView.maxValue = 300;
//    self.videoRecordProgressView.progressList = [@[@13.0f,@13.0f,@3.0f,@288.0f] mutableCopy];
    
//    self.view.layer.borderColor = [UIColor redColor].CGColor;
//    self.view.layer.borderWidth = 3.0f;
//    self.previewView.layer.borderColor = [UIColor blueColor].CGColor;
//    self.previewView.layer.borderWidth = 5.0f;
//    self.previewLayer.borderColor = [UIColor greenColor].CGColor;
//    self.previewLayer.borderWidth = 8.0f;
}
- (void)updateDisplay{
    //相册
    
    //拍照
    if (self.mode == CAMERA_MODE_TAKE_PHOTO) {
        self.thumbButton.hidden = self.photos.count == 0;
        self.photoCountLabel.hidden =  self.thumbButton.hidden;
        self.photoCountLabel.text = [@(self.photos.count) description];
    }
    //视频
    if (self.mode == CAMERA_MODE_SHOOT_VIDEO) {
        self.thumbButton.hidden = self.videoClips.count == 0;
        self.photoCountLabel.hidden =  self.thumbButton.hidden;
        self.photoCountLabel.text = [@(self.videoClips.count) description];
        
        BOOL isRecording =  [self.movieFileOutput isRecording];
        self.timerView.hidden = !isRecording;
        self.devicePositionButton.hidden = isRecording;
        
        NSMutableArray *durationList = [NSMutableArray array];
        for (NSInteger i = 0, n = self.videoClips.count; i < n; i++) {
            PhotoAsset *photoAsset = [self.videoClips objectAtIndex:i];
            [durationList addObject:@(photoAsset.duration)];
        }
        if (isRecording) {
            CMTime currentVideoDuration = self.movieFileOutput.recordedDuration;
            [durationList addObject:@(currentVideoDuration.value*1.0f/currentVideoDuration.timescale)];
        }
        [UIView animateWithDuration:0.1f
                         animations:^{
            CGRect shootButtonFrame = self.shootButton.superview.bounds;
            if (isRecording) {
                shootButtonFrame = CGRectInset(shootButtonFrame, 20, 20);
            }else{
                shootButtonFrame = CGRectInset(shootButtonFrame, 8, 8);
            }
            CGFloat cornerRadius = isRecording ? 5 : shootButtonFrame.size.width/2;
            self.shootButton.frame = shootButtonFrame;
            self.shootButton.layer.cornerRadius = cornerRadius;
            self.videoRecordProgressView.progressList = durationList;
        }
                         completion:^(BOOL finished) {
            
        }];
    }
}
/**
 *  切换模式,初始化界面
 */
- (void)setMode:(NSInteger)mode{
    if (mode == _mode) {
        return;
    }
    if (mode == CAMERA_MODE_TAKE_PHOTO) {
        [self setPhotoOutputActive];
        self.shootButton.backgroundColor = [UIColor whiteColor];
        self.devicePositionButton.hidden = NO;
        
    }
    if (mode == CAMERA_MODE_SHOOT_VIDEO) {
        [self setVideoOutputActive];
        self.shootButton.backgroundColor = [UIColor redColor];
    }
    _mode = mode;
    [self updateDisplay];
}
- (void)startSession {
    if(![self.captureSession isRunning]) {
        [self.captureSession startRunning];
    }
}
- (void)stopSession {
    if([self.captureSession isRunning]) {
        [self.captureSession stopRunning];
    }
}
- (void)updateRecordingDuration{
    NSTimeInterval t = [[NSDate date] timeIntervalSinceDate:self.videoRecordStartDate];
    self.timerLabel.text = [[NSDate dateWithTimeIntervalSince1970:t] format:@"mm:ss"];
    [self updateDisplay];
}
- (NSString *)newVideoStoragePath{
    NSString *fn = PHOTO_RANDOM_FILE_NAME(@"mov");
    NSString *fp = PHOTO_CACHE_FILE(fn);
    return fp;
}
- (void)startRecord {
    if ([self.movieFileOutput isRecording]) {
        return;
    }
    NSString *fp = [self newVideoStoragePath];
    
    AVCaptureConnection *captureConnection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    if(captureConnection.supportsVideoOrientation){
        [captureConnection setVideoOrientation:[self currentVideoOrientation]];
    }
    
    [self.movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:fp] recordingDelegate:self];
    self.videoRecordStartDate = [NSDate date];
    if (self.videoTimer) {
        [self.videoTimer invalidate];
    }
    self.videoTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateRecordingDuration) userInfo:nil repeats:YES];
    [self updateRecordingDuration];
    //
    [self.delegate cameraViewDidStartRecording:self];
}
- (void)stopRecord {
    if ([self.movieFileOutput isRecording]) {
        [self.movieFileOutput stopRecording];
        if ([self.videoTimer isValid]) {
            [self.videoTimer invalidate];
        }
    }
}
- (void)takePhoto{
    AVCapturePhotoOutput * output = (AVCapturePhotoOutput *)self.photoOutput;
    
    //从 AVCaptureStillImageOutput 中取得 AVCaptureConnection
    AVCaptureConnection *captureConnection = [output connectionWithMediaType:AVMediaTypeVideo];
//    if(captureConnection.supportsVideoOrientation){
//        [captureConnection setVideoOrientation:[self currentVideoOrientation]];
//    }
    AVCapturePhotoSettings * settings = [AVCapturePhotoSettings photoSettings];
    settings.highResolutionPhotoEnabled = YES;
//    settings.highResolutionStillImageDimensions = ;
    settings.autoStillImageStabilizationEnabled = YES;
    
    [output capturePhotoWithSettings:settings delegate:self];
}
- (AVCaptureVideoOrientation)currentVideoOrientation {
    AVCaptureVideoOrientation orientation;
    
    switch ([[UIDevice currentDevice] orientation]) {
        case UIDeviceOrientationPortrait:
            orientation = AVCaptureVideoOrientationPortrait;
            break;
        case UIDeviceOrientationLandscapeRight:
            orientation = AVCaptureVideoOrientationLandscapeLeft;
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            orientation = AVCaptureVideoOrientationPortraitUpsideDown;
            break;

        default:
            orientation = AVCaptureVideoOrientationLandscapeRight;
            break;
    }
    
    return orientation;
}
#pragma mark - Action
-(IBAction)clickTakePhotoButton:(id)sender{
    if (self.mode == CAMERA_MODE_TAKE_PHOTO) {
        [self takePhoto];
    }
    if (self.mode == CAMERA_MODE_SHOOT_VIDEO) {
         if ([self.movieFileOutput isRecording]) {
             [self stopRecord];
         }else{
             [self startRecord];
         }
    }
}
- (IBAction)changeCameraPosition:(id)sender{
    @synchronized (self) {
        AVCaptureDevice *videoDevice = nil;
        if (self.videoDevice.position == AVCaptureDevicePositionBack) {
            videoDevice = [self cameraWithPostion:AVCaptureDevicePositionFront];
        }else{
            videoDevice = [self cameraWithPostion:AVCaptureDevicePositionBack];
        }
        NSError *error = nil;
        AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
        if (!error) {
            [self.captureSession beginConfiguration];
            [self.captureSession removeInput:self.videoInput];
            if ([self.captureSession canAddInput:videoInput]) {
                [self.captureSession addInput:videoInput];
                self.videoInput = videoInput;
                self.videoDevice = videoDevice;
            }
            [self.captureSession commitConfiguration];
        }
    }
}
- (IBAction)preview:(id)sender{
//    self.thumbListView.hidden = !self.thumbListView.hidden;
    
    NSArray *photos = nil;
    if (self.mode == CAMERA_MODE_TAKE_PHOTO) {
        photos = self.photos;
    }
    if (self.mode == CAMERA_MODE_SHOOT_VIDEO) {
        photos = self.videoClips;
    }
    PhotoEditPreviewViewController *vc = [[PhotoEditPreviewViewController alloc] initWithPhotos:photos];
    vc.delegate = self;
    BKNavigationController *nav = [[BKNavigationController alloc] initWithRootViewController:vc];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [(UIViewController *)self.delegate presentViewController:nav animated:YES completion:nil];
}
#pragma mark - AVCapturePhotoCaptureDelegate
- (void)savePhoto:(UIImage *)image{
    NSDate *t1 = [NSDate date];
//    image = [image fixOrientation];
    NSString *fn = PHOTO_RANDOM_FILE_NAME(@"png");
    NSString *fp = PHOTO_CACHE_FILE(fn);
    NSTimeInterval costTime = [[NSDate date] timeIntervalSinceDate:t1];
    DLOG(@"savePhoto|fixOrientation|costTime:%f", costTime);
    
    PhotoAsset *photoAsset = [PhotoAsset new];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        BOOL t = [image saveTo:fp];
        if (t) {
            photoAsset.originPath = fp;
        }
    });
    t1 = [NSDate date];
    costTime = [[NSDate date] timeIntervalSinceDate:t1];
    DLOG(@"savePhoto|saveFile|costTime:%f", costTime);
    t1 = [NSDate date];
    photoAsset.width = image.size.width;
    photoAsset.height = image.size.height;
    photoAsset.thumbImage = [image scaleToSize:CGSizeMake(100, 100)];
    costTime = [[NSDate date] timeIntervalSinceDate:t1];
    DLOG(@"savePhoto|scaleToSize|costTime:%f", costTime);
    [self.thumbButton setImage:image forState:UIControlStateNormal];
    [self.photos addObject:photoAsset];
    self.photoCountLabel.text = [@(self.photos.count) description];
    
    [self updateDisplay];
//    [BKIndicator showTips:NSLocalizedString(@"save_success", @"提示") duration:1.0f completion:nil];
    t1 = [NSDate date];
    [PHAsset saveImageToPhotoLib:image resultHandler:^(PHAsset * _Nonnull asset, NSError * _Nonnull error) {
        photoAsset.asset = asset;
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
    }];
    costTime = [[NSDate date] timeIntervalSinceDate:t1];
    DLOG(@"savePhoto|saveImageToPhotoLib|costTime:%f", costTime);
    [self.delegate cameraView:self didTakePhoto:photoAsset];
}
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
    if (error) {
        DLOG(@"captureOutput|error:%@",error.localizedDescription);
    }
    if (photo) {
        if (@available(iOS 11.0, *)) {
            NSDate *t1 = [NSDate date];
            CGImageRef cgImage = [photo CGImageRepresentation];
            UIImageOrientation orientation = UIImageOrientationForCGImagePropertyOrientation([photo.metadata[@"Orientation"] intValue]);
            UIImage * image = [UIImage imageWithCGImage:cgImage scale:1.0f orientation:orientation];
            NSTimeInterval timeCost = [[NSDate date] timeIntervalSinceDate:t1];
            
            DLOG(@"captureOutput|success|iOS:v11.0+|costTime:%f", timeCost);
            [self savePhoto:image];
            
        } else {
            DLOG(@"不是走这个代理方法");
        }
    }
}
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhotoSampleBuffer:(nullable CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(nullable CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(nullable AVCaptureBracketedStillImageSettings *)bracketSettings error:(nullable NSError *)error{
    if (error) {
        DLOG(@"captureOutput|error:%@",error.localizedDescription);
    }
    if (photoSampleBuffer) {
        NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
        UIImage *image = [UIImage imageWithData:data];
        [self savePhoto:image];
    }
}
#pragma mark - AVCaptureFileOutputRecordingDelegate
- (void)captureOutput:(AVCaptureFileOutput *)output didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections{
    DLOG(@"isRecording:%d", [self.movieFileOutput isRecording]);
    [self updateDisplay];
}
- (void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(nullable NSError *)error{
    DLOG(@"%@,isRecording:%d", error, [self.movieFileOutput isRecording]);
    if (error) {
        [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        return;
    }
    if (!error) {
        dispatch_async(dispatch_get_main_queue(), ^{

            PhotoAsset *photoAsset = [PhotoAsset new];
            photoAsset.type = PhotoAssetTypeVideo;
            UIImage *coverImage = [self imageForVideo:outputFileURL atTime:CMTimeMake(1, 1)];
            NSString *fn = PHOTO_RANDOM_FILE_NAME(@"png");
            NSString *fp = PHOTO_CACHE_FILE(fn);
            [coverImage saveTo:fp];
            
            photoAsset.duration = output.recordedDuration.value*1.0f/output.recordedDuration.timescale;
            photoAsset.originImage = coverImage;
            photoAsset.originPath = fp;
            photoAsset.thumbImage = [coverImage scaleToSize:CGSizeMake(200, 200)];
            photoAsset.assetURL = outputFileURL;
            
            [self.videoClips addObject:photoAsset];
            [self.thumbButton setImage:photoAsset.thumbImage forState:UIControlStateNormal];
            
            NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"save_video_clip_finished_msg", @"提示"), self.videoClips.count];
            [BKIndicator showMessage:msg duration:3.0f completion:nil];
            [self.delegate cameraView:self didFinishRecording:photoAsset];
            [self updateDisplay];
        });
        return;
    }
}

-(UIImage *)imageForVideo:(NSURL *)videoURL atTime:(CMTime)time {
    AVAsset *videoAsset = [AVAsset assetWithURL:videoURL];
    
    AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:videoAsset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    //    imageGenerator.maximumSize = CGSizeMake(200, 0);//按比例生成， 不指定会默认视频原来的格式大小
    CMTime actualTime;//获取到图片确切的时间
    NSError *error = nil;
    CGImageRef CGImage = [imageGenerator copyCGImageAtTime:time actualTime:&actualTime error:&error];
    if (!error) {
        UIImage *oriImage = [UIImage imageWithCGImage:CGImage];
//        UIImage *image = [oriImage fixOrientation];
        return oriImage;
//        CMTimeShow(actualTime);   //{111600/90000 = 1.240}
//        CMTimeShow(time); // {1/1 = 1.000}
    }
    return nil;
}
- (void)mergeVideoWithCompletion:(void (^)(NSError *,PhotoAsset*))completion{
    [BKIndicator showMessage:NSLocalizedString(@"video_clip_merge_now", @"提示")];
    [PhotoAsset mergeVideos:self.videoClips
                 toFilePath:[NSURL fileURLWithPath:[self newVideoStoragePath]]
                   progress:^(CGFloat progress) {
        NSInteger p = progress*100;
        [BKIndicator showMessage:[NSString stringWithFormat:@"%@:%ld%%", NSLocalizedString(@"video_clip_merge_now", @"提示"),p]];
    }
                 completion:^(NSError * error, PhotoAsset * photoAsset) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if (!error) {
            [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"video_clip_merge_success", @"提示") completion:nil];
        }
        if (completion) {
            completion(error, photoAsset);
        }
    }];
    
}
#pragma mark - PreviewViewDelegate

- (void)previewViewController:(id)viewController didRemovePhoto:(PhotoAsset*)photo{
    NSMutableArray *array = nil;
    if (self.mode == CAMERA_MODE_TAKE_PHOTO) {
        array = self.photos;
    }
    if (self.mode == CAMERA_MODE_SHOOT_VIDEO) {
        array = self.videoClips;
    }
    NSInteger i = [array indexOfObject:photo];
    [array removeObjectAtIndex:i];
    [self updateDisplay];
    [self.delegate cameraView:self didRemovePhoto:photo];
}


- (void)finishedWithCompletion:(void (^)(NSError *, NSArray *))completion{
    if (self.mode == CAMERA_MODE_TAKE_PHOTO) {
        completion(nil, self.photos);
        return;
    }
    if (self.mode == CAMERA_MODE_SHOOT_VIDEO) {
        [self mergeVideoWithCompletion:^(NSError *error, PhotoAsset *photoAsset) {
            completion(error, photoAsset?@[photoAsset]:nil);
        }];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


@implementation PhotoThumbListView
@synthesize photos = _photos;

- (void) addPhoto:(PhotoAsset *)photoAsset{
    if (!_photos) {
        _photos = [NSMutableArray array];
    }
    if (!_itemViews) {
        _itemViews = [NSMutableArray array];
    }
    CGFloat margin = 10;
    CGFloat closeButtonWidth = 20;
    CGFloat itemWidth = self.bounds.size.height - 2*margin;
    
    CGRect itemFrame = CGRectMake(margin, margin, itemWidth, itemWidth);
    UIView *itemView = [[UIView alloc] initWithFrame:itemFrame];
    
    CGRect thumbButtonFrame = CGRectMake(0, closeButtonWidth/2, itemFrame.size.height - closeButtonWidth/2, itemFrame.size.height - closeButtonWidth/2);
    UIButton *thumbButton = [[UIButton alloc] initWithFrame:thumbButtonFrame];
    [thumbButton setImage:photoAsset.thumbImage forState:UIControlStateNormal];
    [thumbButton addTarget:self action:@selector(preview:) forControlEvents:UIControlEventTouchUpInside];
    thumbButton.layer.cornerRadius = 3;
    thumbButton.clipsToBounds = YES;
    
    CGRect closeButtonFrame = CGRectMake(itemWidth - closeButtonWidth, 0, closeButtonWidth, closeButtonWidth);
    UIButton *closeButton = [[UIButton alloc] initWithFrame:closeButtonFrame];
    [closeButton addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
    
    
    closeButton.backgroundColor = [UIColor redColor];
    closeButton.layer.cornerRadius = closeButtonFrame.size.width/2;
    closeButton.clipsToBounds = YES;
    
    
    [itemView addSubview:thumbButton];
    [itemView addSubview:closeButton];
    [self.contentScrollView addSubview:itemView];
    
    [_itemViews addObject:itemView];
    [_photos addObject:photoAsset];
    [self setNeedsLayout];
}
- (void)removePhoto:(PhotoAsset *)photoAsset{
    NSInteger i = [self.photos indexOfObject:photoAsset];
    [self.photos removeObjectAtIndex:i];
    UIView *v = [self.itemViews objectAtIndex:i];
    [v removeFromSuperview];
    [self.itemViews removeObjectAtIndex:i];
    [self setNeedsLayout];
}
- (void)preview:(UIButton *)button{
    for (NSInteger i = 0, n = self.itemViews.count; i < n; i++) {
        UIView *itemView = [self.itemViews objectAtIndex:i];
        if ([itemView.subviews containsObject:button]) {
            PhotoAsset *photoAsset = [self.photos objectAtIndex:i];
            [self.actionDelegate photoThumbListView:self didClickAtIndex:i withItem:photoAsset];
            break;
        }
    }
}
- (void)remove:(UIButton *)button{
    for (NSInteger i = 0, n = self.itemViews.count; i < n; i++) {
        UIView *itemView = [self.itemViews objectAtIndex:i];
        if ([itemView.subviews containsObject:button]) {
            [itemView removeFromSuperview];
            [self.itemViews removeObject:itemView];
            PhotoAsset *photoAsset = [self.photos objectAtIndex:i];
            [self.photos removeObjectAtIndex:i];
            [self.actionDelegate photoThumbListView:self didRemoveAtIndex:i withItem:photoAsset];
            [self setNeedsLayout];
            break;
        }
    }
}
- (void)layoutSubviews{
    [super layoutSubviews];
    
    CGFloat margin = 10;
    CGFloat itemWidth = self.bounds.size.height - 2*margin;
    [UIView animateWithDuration:0.1f animations:^{
        CGRect itemFrame = CGRectMake(20, margin, itemWidth, itemWidth);
        for (NSInteger i = 0, n = self.itemViews.count; i < n; i++) {
            UIView *itemView = [self.itemViews objectAtIndex:i];
            itemView.frame = itemFrame;
            itemFrame.origin.x += itemFrame.size.width + margin;
        }
        self.contentScrollView.contentSize = CGSizeMake(itemFrame.origin.x + 20, 0);
    }];
}
@end

